//
//  SYLJUserAccount.swift
//  Weibo10
//
//  Created by 刘俊 on 15/10/17.
//  Copyright © 2015年 itheima. All rights reserved.
//

import UIKit

// MARK - 用户账户模型
class SYLJUserAccount: NSObject,NSCoding {

    /// 用于调用access_token，接口获取授权后的access token
    var access_token: String?
    /// access_token的生命周期，单位是秒数
    var expires_in: NSTimeInterval = 0
        {
        didSet {
            expiresDate = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    //此时获取到的时间是距离有效期还剩余的时间,是一个时时刻刻都在变化的时间,不利于做判断,因此需要进行转化,获得最终的有效时间
    var expiresDate: NSDate?
    /// 当前授权用户的UID
    var uid: String?
    //------新添加的用户信息
    /// 用户昵称
    var screen_name: String?
    /// 用户头像地址（大图），180×180像素 
    var avatar_large: String?
    
    init(dict: [String: AnyObject]){
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
 
    // 直接打印模型打印的是内存地址,因此我们可以做一下处理
    override var description: String {
        let keys = ["access_token","expires_in","expiresDate","uid","screen_name","avatar_large"]
        return dictionaryWithValuesForKeys(keys).description
    }
    // MARK: 保存当前对象
    func saveUserAccount() {
        
        var path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last!
        path = (path as NSString).stringByAppendingPathComponent("account.plist")
        print(path)// 在开发中是必须的
        NSKeyedArchiver.archiveRootObject(self, toFile: path)
    }
    
    // MARK: 归档和解档
    /// 归档
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(expiresDate, forKey: "expiresDate")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(screen_name, forKey: "screen_name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
    }
    /// 解档
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token")as? String
        expiresDate = aDecoder.decodeObjectForKey("expiresDate") as? NSDate
        uid = aDecoder.decodeObjectForKey("uid") as? String
        screen_name = aDecoder.decodeObjectForKey("screen_name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
        
        
        
    }
}
